package com.hmdp.service.impl;

import ch.qos.logback.core.util.TimeUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.security.auth.login.LoginContext;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        String code = RandomUtil.randomNumbers(4);
        //保存验证码到session,方便之后从里面取出来做验证
//        session.setAttribute("code", c);
        stringRedisTemplate.opsForValue().set("login:code:" + phone, code,2, TimeUnit.MINUTES);
        log.info("验证码：" + code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String code = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone());
//        String code = session.getAttribute("code").toString();
        if (code==null||!code.equals(loginForm.getCode())) return Result.fail("验证码错误");
        //验证码对了之后到数据库里面查询用户
        //有就登录，没有就是注册，创建新用户
        User user = query().eq("phone", loginForm.getPhone()).one();
        if (user == null) {
            user = new User();
            user.setNickName("user_" + RandomUtil.randomNumbers(5));
            user.setPhone(loginForm.getPhone());
            save(user);
        }
        //将用户保存到session里面
//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        //生成token
        String token = UUID.randomUUID().toString(true);
        //将user对象转换成map对象
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将bean转换成map
//        Map<String,String> userMap=new HashMap<>();
//        userMap.put("phone",user.getPhone());
//        userMap.put("id",user.getId().toString());
//        userMap.put("icon",user.getIcon());
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        //由于long转成string会报错，所以要修改成string类型
//        userMap.put("id",user.getId().toString());
        //一开始只是存入了一个验证码
        //验证通过之后就将token和用户信息存进去
        stringRedisTemplate.opsForHash().putAll("login:token:" + token, userMap);
        //设置过期时间,为了方便测试不设置
//        stringRedisTemplate.expire("login:token:" + token,30, TimeUnit.MINUTES);
        return Result.ok(token);
    }
}
